/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.insta.browser.service.history;

import fr.insta.browser.domain.HistoryEntry;
import fr.insta.browser.domain.IHistoryEntry;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.ImageIcon;

/**
 * Implémentation de service de gestion d'historique avec occurence
 *
 * @author Maarek
 * @version $Id: $Id
 */
public class HistorySingleTabService extends HistoryService implements IHistorySingleTabService {

    private int currentIndex = -1;

    /** {@inheritDoc} */
    @Override
    public void addEntry(String url, String title, ImageIcon icon) {
        IHistoryEntry e = new HistoryEntry(url, title, icon);

        // On supprime les entrées qui sont apres le current index
        int size = entries.size();
        for (int i = currentIndex + 1; i < size; i++) {
            entries.remove(currentIndex + 1);
        }

        entries.add(e);
        currentIndex++;
        fireAddEntry(e);
    }

    /** {@inheritDoc} */
    @Override
    public Iterator<IHistoryEntry> iteratorOfCurrentToEnd() {
        if (currentIndex == -1) {
            return (new ArrayList<IHistoryEntry>()).iterator();
        }
        return entries.subList(currentIndex, entries.size()).iterator();
    }

    /** {@inheritDoc} */
    @Override
    public Iterator<IHistoryEntry> iteratorOfCurrentToBegin() {
        ArrayList<IHistoryEntry> reverse = new ArrayList<>(entries.size());
        for (int i = currentIndex; i >= 0; i--) {
            reverse.add(entries.get(i));
        }
        return reverse.iterator();
    }

    /** {@inheritDoc} */
    @Override
    public boolean hasNext() {
        return !entries.isEmpty() && currentIndex < entries.size() - 1;
    }

    /** {@inheritDoc} */
    @Override
    public boolean hasPrev() {
        return currentIndex > 0;
    }

    /** {@inheritDoc} */
    @Override
    public IHistoryEntry getCurrent() {
        if (currentIndex > -1) {
            return entries.get(currentIndex);
        } else {
            return null;
        }
    }

    /** {@inheritDoc} */
    @Override
    public IHistoryEntry next() {
        if (hasNext()) {
            fireChangeCurrentEntry(entries.get(currentIndex + 1));
            return entries.get(++currentIndex);
        } else {
            return null;
        }
    }

    /** {@inheritDoc} */
    @Override
    public IHistoryEntry prev() {
        if (hasPrev()) {
            fireChangeCurrentEntry(entries.get(currentIndex - 1));
            return entries.get(--currentIndex);
        } else {
            return null;
        }
    }

    /** {@inheritDoc} */
    @Override
    public void moveCurrentTo(IHistoryEntry entry) {
        currentIndex = entries.indexOf(entry);
        fireChangeCurrentEntry(entries.get(currentIndex));
    }
}
